﻿/* ==============================================================================
 * 功能描述：BackpackPanel  
 * 
 * 创 建 者：郑镇泉
 * 
 * 创建日期：2016/4/7 21:54:56
 * ==============================================================================*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using ZZQFrameWork;

/// <summary>
/// 垃圾箱模式
/// </summary>
public enum Enum_TrashType
{
    Normal,SelectTrash,SureTrash
}

/// <summary>
/// 背包类型
/// </summary>
public enum Enum_BagType
{
    One=0,
    Two,
    Three,
    Four,
    Five,
    None
}

/// <summary>
/// 背包子类型
/// </summary>
public enum Enum_SubBagType
{
    Open,Locked
}

public class BackpackPanel : MonoBehaviour
{
    private BackpackModule backpackModule
    {
        get { return ModuleManager.Instance.Get<BackpackModule>(); }
    }

    #region 图集
    /// <summary>
    /// 背包资源图集
    /// </summary>
    private UIAtlas backpackAtlas;

    public UIAtlas BackpackAtlas
    {
        get
        {
            if (backpackAtlas == null)
            {
                backpackAtlas = UIAtlasManager.Instance.GetUIAtlasByName("Backpack_Atlas");
            }
            return backpackAtlas;
        }
    }

    /// <summary>
    /// 装备资源图集
    /// </summary>
    private UIAtlas equipAtlas;

    public UIAtlas EquipAtlas
    {
        get
        {
            if (equipAtlas == null)
            {
                equipAtlas = UIAtlasManager.Instance.GetUIAtlasByName("Equip_Atlas");
            }
            return equipAtlas;
        }
    }

    /// <summary>
    /// 物品资源图集
    /// </summary>
    private UIAtlas goodsAtlas;

    public UIAtlas GoodsAtlas
    {
        get
        {
            if (goodsAtlas == null)
            {
                goodsAtlas = UIAtlasManager.Instance.GetUIAtlasByName("Goods_Atlas");
            }
            return goodsAtlas;
        }
    }

    #endregion

    /// <summary>
    /// 当前显示的背包类型
    /// </summary>
    public Enum_BagType currentBagType=Enum_BagType.One;

    ///// <summary>
    ///// 是否进入丢弃步骤
    ///// </summary>
    //private bool isEnterTrash = false;

    /// <summary>
    /// 垃圾箱图标toggle
    /// </summary>
    private Image trashImage;

    /// <summary>
    /// 进入垃圾模式后高亮背景
    /// </summary>
    private Image selectBgImage;

    /// <summary>
    /// 垃圾箱模式，默认普通
    /// </summary>
    private Enum_TrashType trashType=Enum_TrashType.Normal;

    /// <summary>
    /// 需要丢弃的物品
    /// </summary>
    private List<GoodsItem> trashGoodsList = null;

    /// <summary>
    /// 背包bag集合
    /// </summary>
    private Button[] bagButtons;

    /// <summary>
    /// 背包物品格子grid
    /// </summary>
    private GridLayoutGroup goodsGridLayoutGroup;

    /// <summary>
    /// 物品格子集合
    /// </summary>
    private List<GoodsItem> goodsItemList=new List<GoodsItem>();

    /// <summary>
    /// 当前选择的物品格子
    /// </summary>
    private GoodsItem currentGoodsItem = null;

    /// <summary>
    /// 背包物品格子预设
    /// </summary>
    private GameObject goodsItemPrefab;

    public GameObject GoodsItemPrefab
    {
        get {
            if (goodsItemPrefab == null)
            {
                goodsItemPrefab = ResManager.Instance.Load("GoodsItem") as GameObject;
            }
            return goodsItemPrefab;
        }
    }

    void Awake()
    {
        //获取需要的UI
        trashImage = transform.GetComponentByPath<Image>("Trash");
        selectBgImage = transform.GetComponentByPath<Image>("SelectBG");
        goodsGridLayoutGroup = transform.GetComponentByPath<GridLayoutGroup>("GoodsGrid");
        bagButtons = transform.Find("BagGroup").GetComponentsInChildren<Button>();

        //注册UI事件
        for (int i = 0; i < bagButtons.Length; i++)
        {
            EventTriggerListener.Get(bagButtons[i].gameObject).SetEventHandle(Enum_TouchEventType.OnClick, OnBagButtonClick,i);
        }
        EventTriggerListener.Get(trashImage.gameObject).SetEventHandle(Enum_TouchEventType.OnClick, OnTrashImageClick);
    }

    void Start()
    {
        //创建物品格子
        for (int i = 0; i < 14; i++)
        {
            GoodsItem item = CreatGoodsItem();
            item.Data = null;
            //设置物品格子的点击事件
            EventTriggerListener.Get(item.gameObject).SetEventHandle(Enum_TouchEventType.OnClick, OnGoodsItemButtonClick);
            goodsItemList.Add(item);
        }
        //背包格子初始化为None
        currentBagType = Enum_BagType.None;
        //初始化切换背包到默认（第一个背包）
        OnSwitchBag(Enum_BagType.One);
    }

    #region 界面激活（添加事件） && 隐藏（释放事件） 

    private void OnEnable()
    {
        EventDispatcher.AddListener<GoodsVO>(Events.CharacterEvent.OnAddItem, AddGoods);
        EventDispatcher.AddListener<GoodsVO>(Events.CharacterEvent.OnUpdateItem, UpdateGoods);
        EventDispatcher.AddListener<GoodsVO>(Events.CharacterEvent.OnRemoveItem, RemoveGoods);
        RefreshPanel();
    }

    private void OnDisable()
    {
        EventDispatcher.RemoveListener<GoodsVO>(Events.CharacterEvent.OnAddItem, AddGoods);
        EventDispatcher.RemoveListener<GoodsVO>(Events.CharacterEvent.OnUpdateItem, UpdateGoods);
        EventDispatcher.RemoveListener<GoodsVO>(Events.CharacterEvent.OnRemoveItem, RemoveGoods);
        currentBagType=Enum_BagType.None;
    }

    #endregion

    #region 创建物品格子

    /// <summary>
    /// 创建物品item
    /// </summary>
    /// <returns></returns>
    private GoodsItem CreatGoodsItem()
    {
        GameObject go = Instantiate(GoodsItemPrefab);//创建格子
        go.transform.SetParent(goodsGridLayoutGroup.transform, false);//设置格子父物体
        GoodsItem item = go.GetOrAddComponent<GoodsItem>();//获取格子上的GoodsItem脚本
        item.SetBackpackPanel(this);//设置里面的packPanel
        return item;
    }

    #endregion

    #region 垃圾箱操作

    /// <summary>
    /// 清空垃圾物品集合
    /// </summary>
    private void ClearTrashGoodsList()
    {
        if(trashGoodsList==null)return;//如果垃圾集合为空则返回
        trashGoodsList.Clear();
        trashGoodsList = null;
        SetImageSprite(trashImage.gameObject, BackpackAtlas, "Select_trash");
        trashType=Enum_TrashType.SelectTrash;
    }

    /// <summary>
    /// 丢弃物品
    /// </summary>
    private void DiscardGoods()
    {
        if (trashGoodsList == null || trashGoodsList.Count <= 0) return;//如果垃圾集合为空或者数量小于0，则返回
        Debug.Log("开始丢弃物品。要丢弃的数量："+trashGoodsList.Count);
        //遍历垃圾集合中的物品，并且移除
        for (int i = 0; i < trashGoodsList.Count; i++)
        {
            backpackModule.RemoveGoods(trashGoodsList[i].Data, trashGoodsList[i].Data.count);
            trashGoodsList[i].Data = null;
        }
        ClearTrashGoodsList();
    }
    #endregion

    #region 切换背包

    /// <summary>
    /// 切换背包
    /// </summary>
    /// <param name="type"></param>
    private void OnSwitchBag(Enum_BagType type)
    {
        if(type==currentBagType)return;//如果需要切换到的背包类型=当前背包类型则返回
        Debug.Log("当前切换背包到："+type);
        if ((int) type < backpackModule.openBagCount)//如果点击的是已经解锁的背包
        {
            if(currentBagType!=Enum_BagType.None)//如果当前背包的类型不为空，则把当前背包的图标设置为未开启状态
            SetImageSprite(bagButtons[(int)currentBagType].gameObject, BackpackAtlas, "Normal_bag" + (int)(currentBagType+1));
            currentBagType = type;//设置当前背包为需要开启的背包类型，并且把该背包图标设置成已开启状态
            SetImageSprite(bagButtons[(int)currentBagType].gameObject, BackpackAtlas, "Select_bag" + (int)(currentBagType + 1));
            //Debug.Log(bagButtons[(int)currentBagType]);
            List<GoodsVO> goods = backpackModule.GetGoodsByBagType(type);//通过开启的背包类型从背包模块中获取在该背包类型中的所有物品信息
            if (goods == null)
            {
                Debug.LogError("找不到对应背包的数据，背包类型：" + type);
                return;
            }
            RefreshBag(goods);//刷新背包显示
        }
        else
        {
            Debug.Log("点击的背包还未解锁，请解锁！背包类型："+type);
        }
    }

    /// <summary>
    /// 刷新背包
    /// </summary>
    /// <param name="goods"></param>
    private void RefreshBag(List<GoodsVO> goods )
    {
        Debug.Log("找到的背包有物品数量："+goods.Count);
        for (int i = 0; i < goods.Count; i++)
        {
            goodsItemList[i].Data = goods[i];
        }
    }

    /// <summary>
    /// 设置image的sprite
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="atlas"></param>
    /// <param name="spriteName"></param>

    private void SetImageSprite(GameObject obj,UIAtlas atlas,string spriteName)
    {
        obj.GetComponent<Image>().sprite = atlas.GetSprite(spriteName);
        obj.GetComponent<Image>().SetNativeSize();//重置image的尺寸，设置为sprite原始大小
    }
    #endregion

    #region 格子 增删改查

    /// <summary>
    /// 添加物品
    /// </summary>
    /// <param name="goods"></param>
    private void AddGoods(GoodsVO goods)
    {
        Debug.Log("需要添加物品的类型："+goods.goodsType);
        if (goods.bagType != currentBagType) return;//如果物品所在的背包类型！=当前打开的背包类型，则返回
        GetEmptyItem().Data = goods;//设置格子的数据
    }

    private void UpdateGoods(GoodsVO goods)
    {
        if (goods.bagType != currentBagType) return;//如果物品所在的背包类型！=当前打开的背包类型，则返回
        Debug.Log("开始在背包界面更新物品，物品名称："+goods.name+"物品数量："+goods.count);
        GetItemByUid(goods.uid).Data = goods;//设置格子数据
    }

    private void RemoveGoods(GoodsVO goods)
    {
        if (goods.bagType != currentBagType) return;//如果物品所在的背包类型！=当前打开的背包类型，则返回
        GetItemByUid(goods.uid).Data=null;//设置格子数据
    }

    /// <summary>
    /// 获取当前背包空格子
    /// </summary>
    /// <returns></returns>
    private GoodsItem GetEmptyItem()
    {
        //在物品集合中找到数据为空的格子
        GoodsItem item = goodsItemList.Find(delegate(GoodsItem obj)
        {
            return obj.Data == null;
        });
        if (item == null)
        {
            Debug.Log("当前背包格子已满，当前背包类型：" + currentBagType);
            return null;
        }
        return item;
    }

    /// <summary>
    /// 根据id获取物品格子
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    private GoodsItem GetItemById(int id)
    {
        //在物品集合中找到对应id的格子
        GoodsItem item = goodsItemList.Find(delegate(GoodsItem obj)
        {
            return obj.Data != null && obj.Data.id == id;
        });
        if (item == null)
        {
            Debug.Log("当前背包找不到该id的物品：物品id：" + id);
            return null;
        }
        return item;
    }

    /// <summary>
    /// 根据uid获取物品格子
    /// </summary>
    /// <param name="uid"></param>
    /// <returns></returns>
    private GoodsItem GetItemByUid(int uid)
    {
        //在物品集合中找到对应uid的格子
        GoodsItem item = goodsItemList.Find(delegate(GoodsItem obj)
        {
                return obj.Data != null && obj.Data.uid == uid;
        });
        if (item == null)
        {
            Debug.Log("当前背包找不到该id的物品：物品uid：" + uid);
            return null;
        }
        return item;
    }

    #endregion

    #region 点击事件

    /// <summary>
    /// 背包选择按钮点击
    /// </summary>
    /// <param name="_listener"></param>
    /// <param name="_args"></param>
    /// <param name="_params"></param>
    private void OnBagButtonClick(GameObject _listener, object _args, object[] _params)
    {
        Enum_BagType type = (Enum_BagType) _params[0];//获取点击的Bag类型
        OnSwitchBag(type);//切换到点击的bag
    }

    /// <summary>
    /// 点击垃圾箱图标，进入 && 退出垃圾箱模式
    /// </summary>
    /// <param name="_listener"></param>
    /// <param name="_args"></param>
    /// <param name="_params"></param>
    private void OnTrashImageClick(GameObject _listener, object _args, object[] _params)
    {
        //把普通模式下选择的物品高亮取消
        if(currentGoodsItem!=null)
        currentGoodsItem.SetItemClicked(false);

        if (trashType == Enum_TrashType.Normal)//垃圾类型为普通模式
        {
            SetImageSprite(_listener, BackpackAtlas, "Select_trash");
            selectBgImage.gameObject.SetActive(true);
            trashType = Enum_TrashType.SelectTrash;
        }
        else if (trashType == Enum_TrashType.SelectTrash)//垃圾类型为选择模式
        {
            SetImageSprite(_listener, BackpackAtlas, "Normal_trash");
            selectBgImage.gameObject.SetActive(false);
            trashType = Enum_TrashType.Normal;
        }
        else//垃圾类型为已经选择丢弃物品等待确认丢弃模式
        {
            DiscardGoods();
        }
    }

    /// <summary>
    /// 物品格子按钮点击
    /// </summary>
    /// <param name="_listener"></param>
    /// <param name="_args"></param>
    /// <param name="_params"></param>
    private void OnGoodsItemButtonClick(GameObject _listener, object _args, object[] _params)
    {
        GoodsItem item = _listener.GetComponent<GoodsItem>();
        //根据是否进入垃圾模式来分别判断不同显示方式
        if (trashType==Enum_TrashType.SelectTrash||trashType==Enum_TrashType.SureTrash)
        {
            //当垃圾类型是选择模式或者确认丢弃模式
            OnTrashSelectGoods(item);
        }
        else if(trashType==Enum_TrashType.Normal)
        {
            //当垃圾模式为普通模式
            OnNormalSelectGoods(item);
        }
    }

    /// <summary>
    /// 普通模式下选中物品
    /// </summary>
    /// <param name="item"></param>
    private void OnNormalSelectGoods(GoodsItem item)
    {
        if(item.Data==null)return;
        //Debug.Log("当前点击的物品类型："+item.Data.goodsType);

        if (currentGoodsItem != null) //如果当前物品格子不为空
        {
            currentGoodsItem.SetItemClicked(false);//设置当前格子为未点击
            if (item == currentGoodsItem)
            {
                backpackModule.OnUseGoods(item.Data);
                currentGoodsItem = null;
                return;//如果点击的物品格子就是当前已经选择的物品格子，则返回
            }
        }
        currentGoodsItem = item;//设置当前格子为item
        currentGoodsItem.SetItemClicked(true);//设置当前格子为已点击

        //tips显示该物品详细信息
        EventDispatcher.TriggerEvent(Events.CharacterEvent.OnGoodsTipsShow, item.Data);
        EventDispatcher.TriggerEvent(Events.CharacterEvent.OnEquipInfoPanelShowItemByEquipType,item.Data);
    }

    /// <summary>
    /// 垃圾模式下选中物品
    /// </summary>
    /// <param name="item"></param>
    private void OnTrashSelectGoods(GoodsItem item)
    {
        if(item.Data==null)return;
        //如果垃圾物品集合为空，则实例化
        if (trashGoodsList == null) trashGoodsList = new List<GoodsItem>();
        if (!trashGoodsList.Contains(item))//如果垃圾集合中不存在item
        {
            item.SetItemSelected(true);//设置item为已选择
            trashGoodsList.Add(item);//把item添加到垃圾集合中
        }
        else
        {
            item.SetItemSelected(false);//设置item为未选择
            trashGoodsList.Remove(item);//把item从垃圾集合中移除
        }
        if (trashGoodsList.Count > 0)//如果垃圾集合中的数量大于0
        {
            //垃圾箱图标需要调整为打勾模式
            SetImageSprite(trashImage.gameObject, BackpackAtlas, "Trash_sure");
            trashType = Enum_TrashType.SureTrash;
        }
        else
        {
            //垃圾箱图标需要调整为绿色垃圾箱模式
            SetImageSprite(trashImage.gameObject, BackpackAtlas, "Select_trash");
            trashType = Enum_TrashType.SelectTrash;
        }
    }

    #endregion

    #region 刷新背包

    public void RefreshPanel()
    {
        //通过背包模块中的数据，设置背包界面中的背包显示
        for (int i = 0; i < backpackModule.maxBagCount; i++)
        {
            if (i < backpackModule.openBagCount)
            {
                bagButtons[i].GetComponent<Image>().sprite = BackpackAtlas.GetSprite("Normal_bag" + (i + 1));
            }
            else
            {
                bagButtons[i].GetComponent<Image>().sprite = BackpackAtlas.GetSprite("Lock_bag");
            }
        }

        //初始化切换背包到默认（第一个背包）
        OnSwitchBag(Enum_BagType.One);
    }

    #endregion


}